/**
 *  The Yz.Form class
 */
(function(Yz) {
    if ( typeof(Yz) != "function" ) {
        throw "Failed to identify the root Yz object";
    }

    if ( ! ('Form' in Yz) ) {
        throw "Failed to identify the Yz.Form object";
    }

    // prevent multiple execution
    if ('OneToMany' in Yz.Form) {
        return;
    }

    // TODO actually extend Form.element
    Yz.Form.OneToMany = function(form, elName)
    {
        if (elName in form.elements)
            return form.elements[elName];
        Yz.Form.Element.apply(this, [form, elName]);
    }


    /****************************
     *      Implementation      *
     ****************************/

    Yz.Form.OneToMany.prototype = {

        elementDiv: null,
        dialogDiv: null,
        myId: null, // ?

        init: function() {
            console.log("init: creating Form.OneToMany " + this.name);
            this.elementDiv = $('#FormElement_' + this.name);
            this.dialogDiv = document.createElement("DIV");
            var self = this;
            $(function() {
                console.log("init: assign Form.OneToMany click: " + self.name);
                self.elementDiv.find("a").click(function(){return self.clicked(this)});
            });
        },

        clicked: function(a_clicked) {
            switch (a_clicked.className) {
                case "_edit":
                    this.edit(a_clicked)
                    return false
                case "_delete":
                    this.delete(a_clicked)
                    return false
                case "_add":
                    this.add(a_clicked)
                    return false
            }
            return false
        },

        add: function(a_add) {
            console.log("Form.OneToMany(" + this.name + ").add()");
            return this.dialog(a_add, this.onAdded);
        },
        delete: function(a_delete) {
            console.log("Form.OneToMany(" + this.name + ").delete()");
            return this.dialog(a_delete, this.onDeleted);
        },
        edit: function(a_edit) {
            console.log("Form.OneToMany(" + this.name + ").edit()");
            console.log(document.baseURI);
            //var editURL = this.urls.edit || "../edit-" + this.name;
            //editURL += '/' + a_edit.getAttribute('href').match(/\d+$/)[0];
            return this.dialog(a_edit, this.onModified);
        },
        dialog: function(a_clicked, onSuccessCallback) {
            var self = this;
            var url = a_clicked.getAttribute('href');
            Yz.jqueryui(function(){
                var dlgDiv = self.dialogDiv;
                var buttons = {}
                // TODO buttons from response form submit/reset buttons
                buttons[Yz.translate('OK')] = function() { self.submitForm(this, url, a_clicked, onSuccessCallback); }
                buttons[Yz.translate('Cancel')] = function() { $(this).dialog('close'); }

                $(dlgDiv).load(url, null, function() {
                    var title = $(this).find('h1').text();
                    $(this).find('h1, h2, .yz-form-submit, input[type=submit]').hide();
                    $(this).dialog({
                        width: 450,
                        modal: true,
                        title: title,
                        buttons: buttons
                    }) ;
                })
            });
            return this;
        },
        submitForm: function(div, url, a_clicked, onSuccessCallback) {
            Yz.block()
            var theForm = div.getElementsByTagName("FORM")[0]
            theForm.action = url
            var self = this
            Yz.submitForm(theForm,
                          // onsuccess
                        function(data) {
                            console.log("Form.OneToMany.submitForm(): OK")
                            onSuccessCallback.call(self, a_clicked, data)
                            $(div).dialog("close")

                            // TODO check response div.yz-message
                            Yz.Notify("Complete")
                            Yz.unblock()
                        },
                        // onerror
                        function(xhr, msg) {
                            alert(msg)
                        }
            )
            return this
        },

        onAdded: function(a_clicked, html) {
            console.log("Form.OneToMany.onAdded(): OK")
            // add item to list: add its DIV supplied in html to the list
            alert(html)
            $(a_clicked).before(html)
            this.elementDiv.find("a").click(function(){return self.clicked(this)});
            // TODO do not forget to add click handler to the A in html
            return
        },
        onModified: function(a_clicked, html) {
            console.log("Form.OneToMany.onModified(): OK")
            // modify item: replace its DIV by supplied in html
            alert(html)
            $(a_clicked.parentNode)
                .replaceWith(html)
            this.elementDiv.find("a").click(function(){return self.clicked(this)});
            return
        },
        onDeleted: function(a_clicked, html) {
            console.log("Form.OneToMany.onDeleted(): OK")
            // remove the specified item from list: remove its DIV
            $(a_clicked.parentNode)
                .replaceWith(html)
            return
        }
    }

})(window.Yz);
